package org.example.model.manage.bean.po.security;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;

@Data
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyUserDetails implements UserDetails {

    private User user;

    private List<SysRole> roles;

    private List<SysPermissions> permissions;

    @TableField(exist = false)
    @JsonDeserialize(contentUsing = SimpleGrantedAuthorityDeserializer.class)
    private Collection<SimpleGrantedAuthority> authorities;

    public MyUserDetails(User user, List<SysRole> roles, List<SysPermissions> permissions) {
        this.user = user;
        this.roles = roles;
        this.permissions = permissions;
    }


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        authorities = new HashSet<SimpleGrantedAuthority>();
        if(!CollectionUtil.isEmpty(this.permissions)) {
            for (SysPermissions permission : permissions) {
                authorities.add(new SimpleGrantedAuthority(permission.getAccessName()));
            }
        }

        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getAccount();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}